<template>

  <div>
    <div class="selector">
      <div class="time-select">
        <span class="demonstration"/>
        <el-date-picker
                v-model="value2"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions">
        </el-date-picker>
      </div>

      <div class="build-select" v-if="jurisdiction">


        <el-select v-model="value" clearable placeholder="请选择">
          <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
          </el-option>
        </el-select>
      </div>

      <el-button type="success" @click="conditionSearch">筛选</el-button>
      <el-button type="success" icon="el-icon-download" @click="exportExcel">导出excel表格</el-button>
      <el-button type="success" :loading="isLoding" @click="refreshOnHand">{{lodingData}}</el-button>
      <el-switch
              class="autorefresh"
              v-model="switch1"
              :width='40'
              active-color="#67C23A"
              inactive-text="自动刷新提醒">
      </el-switch>
    </div>

    <el-table
            :data="tableData"
            class="table">
      <el-table-column
              label="教学楼"
              width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.build }}</span>
        </template>
      </el-table-column>
      <el-table-column
              label="课室"
              width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.classroom }}</span>
        </template>
      </el-table-column>
      <el-table-column
              label="报障时间"
              width="180">
        <template slot-scope="scope">
          <span>{{ formatTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
              label="类型"
              width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column
              label="时限要求"
              width="110">
        <template slot-scope="scope">
          <span>{{ scope.row.limit }}</span>
        </template>
      </el-table-column>
      <el-table-column
              label="最后更新时间"
              width="160">
        <template slot-scope="scope">
          <span>{{ formatTime(scope.row.solveTime) }}</span>
        </template>
      </el-table-column>


      <el-table-column
              label="处理结果"
              width="100">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>备注: {{ scope.row.note }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.result }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
              label="处理人"
              width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.solver }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">r
        <template slot-scope="scope">
          <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row), dialogFormVisible = true">编辑
          </el-button>
          <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row), dialogVisible = true"

          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="编辑信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="教学楼" :label-width="formLabelWidth">
          <el-select v-model="form.build" placeholder="请选择教学楼">
            <el-option label="定静楼一" value="定静楼一"></el-option>
            <el-option label="定静楼二" value="定静楼二"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课室" :label-width="formLabelWidth">
          <el-input class="input" v-model="form.classroom" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="处理结果" :label-width="formLabelWidth">
          <el-select v-model="form.result" placeholder="请选择处理结果">
            <el-option label="已解决" value="已解决"></el-option>
            <el-option label="正在处理" value="正在处理"></el-option>
            <el-option label="未解决" value="未解决"></el-option>
          </el-select>
        </el-form-item>
        <div style="display: flex; margin-left: 50px; margin-bottom: 20px">
          <el-checkbox v-model="checked">是否发送消息提醒(订阅消息只能发送一次)</el-checkbox>

          <el-switch class="customize"
                     v-if="checked"
                     v-model="customize"
                     active-text="自定义模板消息"
                     active-color="#13ce66"
                     inactive-color="#ff4949">
          </el-switch>
        </div>
        <div v-if="customize" class="customize_input_group">
          <el-input class="customize_input1" v-model="message_build" placeholder="教学楼"></el-input>
          <el-input class="customize_input2" v-model="message_classroom" placeholder="教室号"></el-input>
          <el-input class="customize_input3" v-model="message_reamrk" placeholder="处理结果"></el-input>
        </div>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="form.note" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="UpdateData(), dialogFormVisible = false ">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose">
      <span>确认删除吗?</span>
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="deleteData(), dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <div class="block">

      <el-pagination
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage3"
              :page-size="10"
              layout="prev, pager, next, jumper"
              :total="CalcPages">
      </el-pagination>
    </div>
    <audio controls="controls" hidden src="../../assets/tips.mp3" ref="audio"/>

  </div>
</template>

<script>
  import moment from 'moment'
  import {
    conditionGet,
    getConditionNum,
    deleteTableData,
    updateTableData,
    fileExport
  } from "../../network/obstacleTable";
  import {sendMessage} from "../../network/sendSubscription";

  moment.locale('zh-cn');
  export default {
    data() {
      return {
        switch1: false,
        options: [{
          value: '定静楼一',
          label: '定静楼一'
        }, {
          value: '定静楼二',
          label: '定静楼二'
        }, {
          value: '定静楼三',
          label: '定静楼三'
        }, {
          value: '定静楼四',
          label: '定静楼四'
        }],
        value: '',
        isLoding: false,
        lodingData: '点击手动刷新',
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value2: '',
        tableData: [],
        dialogFormVisible: false,
        form: {
          build: '',
          result: '',
          classroom: '',
          note: ''
        },
        formLabelWidth: '120px',
        currentIndex: 0,
        dialogVisible: false,
        currentPage3: 1,
        pageNum: 0,
        newPageNum: 0,
        page: 1,
        mathGap: 0,
        exprotData: [],
        checked: false,
        customize: false,
        message_build: '',
        message_classroom: '',
        message_reamrk: ''
      }
    },
    created() {
      this.setBuild()
      this.getConditionNum(this.value2, this.value)
      this.conditionGet(this.value2, this.value, this.page)
      this.switch1 = false

    },
    deactivated() {
      // console.log('deactivated');
      this.switch1 = false
    },
    destroyed() {
      // console.log('destroyed');
      this.switch1 = false
    },


    methods: {
      handleEdit(index, row) {
        // console.log(index, row);
        this.checked = false
        this.switch1 = false
        this.currentIndex = index
        this.form.build = this.tableData[this.currentIndex].build
        this.form.classroom = this.tableData[this.currentIndex].classroom
        this.form.result = this.tableData[this.currentIndex].result
        this.form.note = this.tableData[this.currentIndex].note
      },
      handleDelete(index, row) {
        // console.log(index, row);
        this.switch1 = false
        this.currentIndex = index
      },
      UpdateData() {

        this.tableData[this.currentIndex].build = this.form.build
        this.tableData[this.currentIndex].classroom = this.form.classroom
        this.tableData[this.currentIndex].result = this.form.result
        this.tableData[this.currentIndex].note = this.form.note
        // 服务器上行api
        this.$options.methods.updateTableData(this.tableData[this.currentIndex]._id, this.form.build, this.form.classroom, this.form.result, this.form.note, this.$store.getters.user.name)
        if (this.checked) {
          this.sendMessage(this.tableData[this.currentIndex].openid, this.message_build, this.message_classroom, this.message_reamrk)
        }
        setTimeout(() => {
          this.getConditionNum(this.value2, this.value)
          this.conditionGet(this.value2, this.value, this.page)
        }, 300)
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      deleteData() {
        this.$options.methods.deleteTableData(this.tableData[this.currentIndex]._id)
        this.tableData.splice(this.currentIndex, 1)
        this.getConditionNum(this.value2, this.value)
        this.conditionGet(this.value2, this.value, this.page)
      },
      handleCurrentChange(val) {
        this.page = val
        this.conditionGet(this.value2, this.value, val)
      },
      conditionSearch() {
        this.conditionGet(this.value2, this.value, this.page),
          this.getConditionNum(this.value2, this.value)
      },
      setBuild() {
        if (this.$store.getters.user !== '超级管理员') {
          this.value = this.$store.getters.user.build
        }
      },
      open(message) {
        this.$notify.success({
          title: '新报障',
          message: message,
          showClose: false
        });
      },
      formatTime(time) {
        if (time) {
          time = moment(time).format('YYYY-MM-DD HH:mm:ss')
          return time
        }
        return ''
      },

      formatTime1(time) {
        if (time) {
          time = moment(time).format('YY/MM/DD HH:mm:ss')
          return time
        }
        return ''
      },

      listenDbChange() {
        // console.log('调用');
        this.refresh(this.value2, this.value)
        if (this.newPageNum > localStorage.count) {
          // console.log(this.newPageNum);
          // console.log(localStorage.count);

          // console.log('有' + (this.newPageNum - localStorage.count) +'条数据更新');
          this.mathGap = this.newPageNum - localStorage.count
          this.$refs.audio.currentTime = 0; //从头开始播放提示音
          this.$refs.audio.play();
          this.conditionGet()


          localStorage.count = this.newPageNum
        }

        if (!this.switch1) return
        setTimeout(() => {
          if (this.switch1) {
            this.listenDbChange()
            // console.log('延迟程序调用');
          }
          if (this.mathGap) {
            for (let i = 0; i < this.mathGap; i++) {
              setTimeout(() => {
                this.open(this.tableData[i].classroom)
              }, 1000)
            }
            this.mathGap = 0
          }
        }, 5000)
      },
      refreshOnHand() {
        this.isLoding = true,
          this.lodingData = '刷新中',
          this.getConditionNum(this.value2, this.value)
        this.conditionGet(this.value2, this.value, this.page)
        setTimeout(() => {
          this.isLoding = false
          this.lodingData = '点击手动刷新'
          this.$message({
            message: '刷新成功',
            type: 'success'
          });
        }, 800)
      },

      exportExcel() {
        this.fileExport(this.value2, this.value)
      },

      export2Excel() {

        require.ensure([], () => {

          const {export_json_to_excel} = require('../../vendor/Export2Excel');


          const tHeader =

            [

              '楼号', '教室号', '报障时间', '类型', '最后更新时间', '时限要求', '处理结果','处理人', '备注'

            ];

          const filterVal =

            ['build', 'classroom', 'createTime', 'type', 'solveTime', 'limit', 'result','solver', 'note'];

          const list = this.exprotData;

          for (let i = 0; i < list.length; i++) {
            list[i].createTime = this.formatTime1(list[i].createTime)
            if (list[i].solveTime) {
              list[i].solveTime = this.formatTime1(list[i].solveTime)
            }
          }

          const data = this.formatJson(filterVal, list);

          let export_time = ''

          let export_build = ''

          if (!this.value) {
            export_build = '所有教学楼'
          } else {
            export_build = this.value
          }

          if (!this.value2) {
            export_time = '全部时间'
          } else {
            export_time = this.value2[0] + '-' + this.value2[1]
            this.formatTime1(export_time)
          }

          export_json_to_excel(tHeader, data, export_time + export_build + '报障表');

        })

      },

      formatJson(filterVal, jsonData) {

        return jsonData.map(v => filterVal.map(j => v[j]))

      },


      /**
       * 网络请求相关方法
       */


      getConditionNum(date, build) {
        getConditionNum(date, build).then(res => {
          // console.log(res);
          this.pageNum = res
          localStorage.setItem('count', res)
        })
      },

      refresh(date, build) {
        getConditionNum(date, build).then(res => {
          // console.log(res);
          this.newPageNum = res
        })
      },


      deleteTableData(id) {
        // console.log(id)
        deleteTableData(id).then(res => {
          // console.log(res);
        })
      },

      updateTableData(id, build, classroom, result, note, solver) {
        updateTableData(id, build, classroom, result, note, solver).then(res => {
          // console.log(res);
        })
      },

      conditionGet(date, build, page) {
        conditionGet(date, build, page).then(res => {
          // console.log(res);
          // this.pageNum = res.number[0].num
          this.tableData = res
        })
      },

      fileExport(date, build) {
        fileExport(date, build).then(res => {
          this.exprotData = res
          this.export2Excel()
        })
      },

      sendMessage(openid, build, classroom, remark) {
        sendMessage(openid, build, classroom, remark).then(res => {
          if (res.errcode === 0) {
            this.$message({
              message: '通知成功',
              type: 'success'
            })
          } else {
            this.$message.error('通知失败，可能不是首次或对方拒接');
          }
        })
      }
    },


    computed: {
      /**
       * @return {number}
       */
      CalcPages() {
        return this.pageNum
      }
      ,
      jurisdiction() {
        return this.$store.getters.user.identity === '超级管理员';
      }
    }
    ,
    watch: {
      value2(val) {
        if (val === null) {
          this.value2 = ''
        }
      },
      switch1(val) {
        if (val === true) {
          // console.log('switch调用监听');
          this.listenDbChange()
        }
      },
      checked(val) {
        if (val === true) {

          this.message_build = this.form.build
          this.message_classroom = this.form.classroom
          this.message_reamrk = '课室管理员正在快马加鞭赶来，请耐心等待'
        } else {
          this.customize = false
        }
      }
    }
  }
</script>

<style>
  .selector {
    display: flex;
    text-align: left;
    margin-left: 1%;
    margin-top: 2%;
  }

  .table {

    width: 98%;
    margin: 0 auto;
    margin-top: 1%;
    border: 1px solid #eee;
    border-radius: 4px;

  }

  .input {
    width: 30%;
  }

  .block {
    margin-top: 2%;
    width: 98%;
    text-align: right;
  }

  .time-select {
    margin-top: -0px;
  }

  .build-select {

    margin-left: 10px;
  }

  .el-button--success {
    height: 40px;
    margin-left: 10px;
  }

  .autorefresh {
    margin-top: 0.8%;
    margin-left: 2%;
  }

  .customize {
    margin-left: 30px;

  }

  .customize_input_group {
    width: 50%;
    margin-left: 50px;
  }

  .customize_input1 {
    margin-bottom: 20px;
    width: 30%;
  }

  .customize_input2 {
    margin-left: 20px;
    margin-bottom: 20px;
    width: 30%;
  }

  .customize_input3 {
    margin-bottom: 20px;
  }
</style>